﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using Frame.Lib.Common;
using System.Web.UI;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Data;

namespace Frame.Lib.Utilities
{
    public sealed class GVUtil
    {
        private GVUtil() { }

        #region GridView里的编辑按钮的代码
        /// <summary>
        /// GridView里的编辑按钮的代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="strEditUrl"></param>
        public static void SetEdit(object sender, GridViewRowEventArgs e, int width, int height, string strEditUrl)
        {
            GridView gvList = (GridView)sender;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string strID = StrUtil.EncryptUrl(gvList.DataKeys[e.Row.RowIndex]["ID"].ToString());
                HyperLink lnkName = (HyperLink)e.Row.FindControl("lnkName");
                HyperLink lnkEdit = (HyperLink)e.Row.FindControl("lnkEdit");
                if (strEditUrl == null)
                {
                    strEditUrl = GlobalVar.WebCurrPath + "Edit.aspx?ID=" + strID;
                }
                if (lnkName != null)
                {
                    lnkName.NavigateUrl = "javascript:;";

                    JSUtil.ShowForm(lnkName, "修改", null, strEditUrl, width, height);
                }
                if (lnkEdit != null)
                {
                    lnkEdit.NavigateUrl = "javascript:;";

                    JSUtil.ShowForm(lnkEdit, "修改", null, strEditUrl, width, height);
                }
            }
        }

        public static void SetEdit(object sender, GridViewRowEventArgs e, int width, int height)
        {
            SetEdit(sender, e, width, height, null);
        }
        #endregion

        #region 初始化GridView
        /// <summary>
        /// 初始化GridView
        /// </summary>
        /// <param name="gv"></param>
        public static void InitGV(GridView gvList)
        {
            gvList.EnableViewState = false;
            gvList.EmptyDataText = "没有数据";
            gvList.EmptyDataRowStyle.CssClass = "empty";
            gvList.RowDataBound += new GridViewRowEventHandler(gv_RowDataBound);
            gvList.RowCreated += new GridViewRowEventHandler(gv_RowCreated);
        }

        static void gv_RowCreated(object sender, GridViewRowEventArgs e)
        {
            GridView gvList = (GridView)sender;
            Literal litIndex = (Literal)e.Row.FindControl("litIndex");
            if (litIndex != null)
            {
                litIndex.Text = (e.Row.RowIndex + gvList.PageSize * gvList.PageIndex + 1).ToString();
            }
        }

        static void gv_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            GridView gvList = (GridView)sender;

            if (e.Row.RowType == DataControlRowType.Header)
            {
                CheckBox chkSelectAll = (CheckBox)e.Row.FindControl("chkSelectAll");
                if (chkSelectAll != null)
                {
                    chkSelectAll.Attributes.Add("onclick", "SelectAll(" + gvList.ClientID + ")");
                }
                e.Row.Cells[e.Row.Cells.Count - 1].Style.Add("border-right-width", "0px");

                foreach (TableCell cell in e.Row.Cells)
                {
                    cell.Wrap = false;
                }

            }
            else if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Cells[e.Row.Cells.Count - 1].Style.Add("border-right-width", "0px");//隐藏最右边一个单元格右边一个边框 
                CheckBox chkSelect = (CheckBox)e.Row.FindControl("chkSelect");
                HiddenField hidSelectIDs = (HiddenField)gvList.Parent.FindControl("hidSelectIDs");
                if (chkSelect != null)
                {
                    e.Row.Attributes.Add("onclick", "SelectTr('" + chkSelect.ClientID + "');");

                    if (hidSelectIDs != null)
                    {
                        string strID = gvList.DataKeys[e.Row.RowIndex]["ID"].ToString();

                        Control ctlUpperID = e.Row.FindControl("hidUpperID");//主要用于移动树状目录时判断是否选择了同一级目录
                        if (ctlUpperID != null)
                        {
                            strID = strID + "|" + ((HiddenField)ctlUpperID).Value;
                        }
                        chkSelect.Attributes.Add("onclick", "SetSelectID('" + hidSelectIDs.ClientID + "','" + strID + "')");
                    }

                }

                TextBox txtOrders = (TextBox)e.Row.FindControl("txtOrders");//处理排序
                if (txtOrders != null)
                {
                    string strID = gvList.DataKeys[e.Row.RowIndex]["ID"].ToString();
                    HiddenField hidOrders = (HiddenField)gvList.Parent.FindControl("hidOrders");
                    txtOrders.Attributes.Add("onchange", "SetOrders(document.all." + hidOrders.ClientID + "," + strID + ",this)");
                    txtOrders.Attributes.Add("onmouseover", "this.className = 'over'");
                    txtOrders.Attributes.Add("onmouseout", "this.className = 'out'");
                    txtOrders.Attributes.Add("onfocus", "this.className = 'focus'");
                    txtOrders.Attributes.Add("onblur", "ValidateOrders(this)");
                }

                if (e.Row.Attributes["onmouseover"] == null)
                {
                    e.Row.Attributes.Add("onmouseover", "oldbg=this.className;this.className='trover';");
                    e.Row.Attributes.Add("onmouseout", "this.className=oldbg;");
                }
            }
            else if (e.Row.RowType == DataControlRowType.EmptyDataRow)
            {
                //e.Row.Cells[0].Style["border-bottom-width"] = "0px;";
                //e.Row.Cells[0].CssClass = "empty";
                //e.Row.Cells[0].Style["border-top"] = "solid 1px #d7d7d7";
            }
        }
        #endregion

        #region 导出Excel
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="gvList"></param>
        /// <param name="fileName"></param>
        public static void ExportExcel(GridView gvList, string fileName)
        {
            Page page = gvList.Page;
            string attachment = "attachment; filename=" + page.Server.UrlEncode(fileName) + ".xls";
            page.Response.ClearContent();
            page.Response.AddHeader("content-disposition", attachment);
            page.Response.ContentType = "application/ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            HtmlForm frm = new HtmlForm();
            gvList.Page.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(gvList);

            frm.RenderControl(htw);
            page.Response.Write(sw.ToString());
            page.Response.End();
        }
        #endregion

        #region 树状列表在回传以后还原折叠状态
        /// <summary>
        /// 树状列表在回传以后还原折叠状态
        /// </summary>
        /// <param name="gvList"></param>
        /// <param name="hidHideTrIDs"></param>
        public static void RestoreTreeListState(GridView gvList, HiddenField hidHideTrIDs)
        {
            string strHideIDs = hidHideTrIDs.Value;
            List<string> lstIDFlags = StrUtil.SplitToStr(strHideIDs);
            Dictionary<int, string> htIDs = new Dictionary<int, string>();//把ID和flag分开

            foreach (string str in lstIDFlags)
            {
                string[] tmp = str.Split('|');
                htIDs.Add(int.Parse(tmp[0]), tmp[1]);
            }
            for (int i = 0; i < gvList.Rows.Count; i++)
            {
                int id = (int)gvList.DataKeys[i]["ID"];
                if (htIDs.ContainsKey(id))
                {
                    gvList.Rows[i].Style.Add("display", "none");
                    gvList.Rows[i].Attributes.Add("flag", htIDs[id]);
                }

                if (SubRowIsHide(i, htIDs, gvList))//判断它是否有子行，如有则判断子行是否显示，如不显示则图片变为“+”号
                {
                    Literal litSpace = (Literal)gvList.Rows[i].FindControl("litSpace");
                    litSpace.Text = litSpace.Text.Replace("-.jpg", "+.jpg");
                }
            }
        }

        private static bool SubRowIsHide(int rowIndex, Dictionary<int, string> htIDs, GridView gvList)
        {
            bool flag = false;
            DataView dv = (DataView)gvList.DataSource;
            int id = (int)gvList.DataKeys[rowIndex]["ID"];

            dv.RowFilter = "UpperID = " + id;
            if (dv.Count > 0)
            {
                int firstSubID = (int)dv[0]["ID"];
                if (htIDs.ContainsKey(firstSubID))//子行在隐藏之列
                {
                    flag = true;
                }
            }
            return flag;
        }
        #endregion


    }
}
